'use strict';

/**
 * 通用接口 - controller
 */

const { Controller } = require('egg');
const path = require('path');
const fs = require('fs');
const sendToWormhole = require('stream-wormhole');
const uuid = require('node-uuid');
const Captchapng = require('captchapng');

/**
 * 保存文件流
 * @param {object} stream 文件流
 * @param {string} filePath 保存路径
 *
 * @return {function} promise
 **/
function saveStream(stream, filePath) {
  return new Promise((resolve, reject) => {
    const ws = fs.createWriteStream(filePath);
    stream.pipe(ws);
    stream.on('error', reject);
    stream.on('end', resolve);
  });
}

class UtilsController extends Controller {
  async upload() {
    const { ctx } = this;

    ctx.logger.info('**********上传图片**********');
    const stream = await ctx.getFileStream();

    // const basename = path.basename(stream.filename);
    const basename = uuid.v1().replace(/-/g, '') + '.' + stream.filename.split(/(.+)(\.)/)[3];
    const name = path.resolve(__dirname, '../public/img', basename);
    console.log(name);
    
    try {
      await saveStream(stream, name);

    } catch (err) {
      await sendToWormhole(stream);
      throw err;
    }

    ctx.body = {
      url: "/img/" + basename,
    };
  }

  /** 登录 **/
  async login() {
    const { ctx, service } = this;

    // 校验接口参数是否正确
    ctx.validate({
      account: 'string',
      password: 'string',
      //captch: 'string',
    }, {
      account: ctx.request.body.account,
      password: ctx.request.body.password,
      //captch: ctx.request.body.captch,
    });

    ctx.logger.info(`***************用户登录：账号(${ctx.request.body.account})***************`);
    try {
      const result = await ctx.model.User
          .findOne({
            account: ctx.request.body.account,
            password: ctx.request.body.password // ctx.helper.md5(ctx.request.body.password || ''),
          }).populate({path : "role",populate : {path : "permissions"}}),
        captch = ctx.request.body.captch;

      if (result && parseInt(captch) === ctx.session.captch) {
        // 调用 rotateCsrfSecret 刷新用户的 CSRF token
        ctx.rotateCsrfSecret();
        ctx.cookies.set('csrfToken', ctx.session.csrfToken, {
          httpOnly: false, // 默认就是 true
          encrypt: false, // 加密传输
        });

        ctx.session.account = result.account;
        ctx.session.role = result.role;
        ctx.session.maxAge = 30 * 60 * 1000; // 有效期半小时
        delete ctx.session.captch;

        ctx.body = {
          errMessage: null,
          errCode: null,
          status: 'ok',
        };
      } else if (parseInt(captch) !== ctx.session.captch) {
        ctx.body = {
          errMessage: '验证码错误',
          errCode: null,
          status: 'fail',
        };
      } else {
        ctx.body = {
          errMessage: '账号或密码错误',
          errCode: null,
          status: 'fail',
        };
      }

      // const User = new ctx.model.User({
      //   account: ctx.request.body.account,
      //   password: ctx.helper.md5(ctx.request.body.password),
      // });
      //
      // const result = await User.save();
      // ctx.success(result);

    } catch (err) {

      ctx.error(err);
    }
  }

  /** 登出 **/
  async logout() {
    const { ctx } = this;

    try {
      ctx.session = null;

      ctx.success('ok');
    } catch (err) {
      ctx.logger.error('**********登出错误**********');
      ctx.logger.error(err);
      ctx.error(err);
    }
  }

  /** 验证码 **/
  async captch() {
    let captch_code = '';
    const { ctx } = this;

    try {
      do {
        captch_code = (Math.random() + '').substring(5, 11);
      } while (parseInt(captch_code) < 100000);

      const p = new Captchapng(115, 35, parseInt(captch_code));
      p.color(0, 0, 0, 0);
      p.color(255, 255, 255, 255);

      const img = p.getBase64();
      ctx.session.captch = parseInt(captch_code);
 
      console.log(`***********验证码：${ctx.session.captch}***********`)

      ctx.success({
        url: 'data:image/png;base64,' + img,
      });

    } catch (err) {

      ctx.error(err);
    }
  }

  /** 修改密码 **/
  async chgPwd() {
    const { ctx, service } = this;
    ctx.validate({
      user: /[a-z0-9]{24}/,
      oldPwd: 'string',
      newPwd: 'string',
    }, {
      user: ctx.request.body.user,
      oldPwd: ctx.request.body.oldPwd,
      newPwd: ctx.request.body.newPwd,
    });

    try {
      const result = await service.user._findOne({ _id: ctx.request.body.user });
      if (!result) {
        ctx.fail('未找到该用户');
      } else if (result.password !== ctx.helper.md5(ctx.request.body.oldPwd)) {
        ctx.fail('旧密码错误');
      } else {
        await service.user.update({
          cond: { _id: ctx.request.body.user },
          set: {
            $set: { password: ctx.helper.md5(ctx.request.body.newPwd) },
          },
        });
        ctx.success('修改密码成功！');
      }
    } catch (err) {
      ctx.logger.error('**********修改密码错误**********');
      ctx.logger.error(err);
      ctx.error(err);
    }
  }

  /**角色信息修改 */
  async updateRole() {
    const { ctx } = this;

    try {
      const result = await ctx.model[Model]
        .update({ _id: ctx.params.id }, { $set: ctx.request.body });

      ctx.success(result);

    } catch (err) {
      ctx.logger.error(err);
      ctx.error(err);
    }
  }
}

module.exports = UtilsController;
